import { render, Element, setAttr } from './element';

let allPatches;
let index = 0;
/**
 *
 * @param {*} node render 后的真实dom节点
 * @param {*} patches 需要被补丁到真实dom上的虚拟dom
 */
export function patch(node, patches) {
  // 给某个元素打补丁
  allPatches = patches;
  walk(node);
}

function walk(node) {
  let currentPatch = allPatches[index++];
  let childNodes = node.childNodes;
  childNodes.forEach((child) => walk(child));
  if (currentPatch.length > 0) {
    doPatch(node, currentPatch);
  }
}

function doPatch(node, patches) {
  patches.forEach((patch) => {
    switch (patch.type) {
      case 'ATTRS':
        for (let key in patch.attrs) {
          let value = patch.attrs[key];
          if (value) {
            setAttr(node, key, value);
          } else {
            node.removeAttribute(key);
          }
        }
        break;
      case 'TEXT':
        node.textContent = patch.text;
        break;
      case 'REPLACE':
        let newNode =
          patch.newNode instanceof Element
            ? render(patch.newNode)
            : document.createTextNode(patch.newNode);
        node.parentNode.replaceChild(newNode, node);
        break;
      case 'REMOVE':
        break;
    }
  });
}

// flex: 1;
// css 三角形
// svg 深入
//
